package com.song.druid.exception.hadler;

import com.song.druid.exception.ListGroupVaildException;
import com.song.druid.result.ResultEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.Path;
import javax.validation.ValidationException;
import java.util.*;

@RestControllerAdvice
public class ListGroupVaildExceptionHandler {
    @ExceptionHandler(ValidationException.class)
    public ResultEntity listGroupVaildException(ValidationException validationException){
        Map<Integer, Map<String, String>> errorMap = new HashMap<>();
        Throwable throwable = validationException.getCause();
        ListGroupVaildException listGroupVaildException = (ListGroupVaildException) throwable;
        Map<Integer, Set<ConstraintViolation<Object>>> errors = listGroupVaildException.getErrors();
        errors.forEach((k, v) -> {
            Map<String, String> map = new HashMap<>();
            v.stream().forEach(cv -> {
                Iterator<Path.Node> iterator = cv.getPropertyPath().iterator();
                while (iterator.hasNext()){
                    Path.Node next = iterator.next();
                    String name = next.getName();
                    map.put(name, cv.getMessage());
                }
            });
            errorMap.put(k, map);
        });
        return ResultEntity.failDataMessage(errorMap, "批量数据验证失败");
    }
}
